package vector

import (
	"github.com/qdrant/go-client/qdrant"
)

// convertToQdrantFilter 将vector包的Filter转换为qdrant.Filter
func convertToQdrantFilter(filter *Filter) *qdrant.Filter {
	if filter == nil {
		return nil
	}
	
	qdrantFilter := &qdrant.Filter{
		Must:     make([]*qdrant.Condition, 0),
		MustNot:  make([]*qdrant.Condition, 0),
		Should:   make([]*qdrant.Condition, 0),
	}
	
	// 转换Must条件
	for _, cond := range filter.Must {
		if qdrantCond := convertToQdrantCondition(&cond); qdrantCond != nil {
			qdrantFilter.Must = append(qdrantFilter.Must, qdrantCond)
		}
	}
	
	// 转换MustNot条件
	for _, cond := range filter.MustNot {
		if qdrantCond := convertToQdrantCondition(&cond); qdrantCond != nil {
			qdrantFilter.MustNot = append(qdrantFilter.MustNot, qdrantCond)
		}
	}
	
	// 转换Should条件
	for _, cond := range filter.Should {
		if qdrantCond := convertToQdrantCondition(&cond); qdrantCond != nil {
			qdrantFilter.Should = append(qdrantFilter.Should, qdrantCond)
		}
	}
	
	return qdrantFilter
}

// convertToQdrantCondition 将vector包的Condition转换为qdrant.Condition
func convertToQdrantCondition(condition *Condition) *qdrant.Condition {
	if condition == nil || condition.Match == nil {
		return nil
	}
	
	// 根据值的类型选择适当的匹配函数
	switch v := condition.Match.Value.(type) {
	case string:
		// 对于file_path字段，使用文本匹配而不是关键字匹配
		if condition.Key == "file_path" {
			return qdrant.NewMatchText(condition.Key, v)
		}
		return qdrant.NewMatchKeyword(condition.Key, v)
	case int:
		return qdrant.NewMatchInt(condition.Key, int64(v))
	case int64:
		return qdrant.NewMatchInt(condition.Key, v)
	case bool:
		return qdrant.NewMatchBool(condition.Key, v)
	case float64:
		return qdrant.NewMatchInt(condition.Key, int64(v))
	case float32:
		return qdrant.NewMatchInt(condition.Key, int64(v))
	default:
		// 尝试转换为字符串匹配
		if str, ok := v.(string); ok {
			// 对于file_path字段，使用文本匹配而不是关键字匹配
			if condition.Key == "file_path" {
				return qdrant.NewMatchText(condition.Key, str)
			}
			return qdrant.NewMatchKeyword(condition.Key, str)
		}
	}
	
	return nil
}

// NewFilter 创建新的过滤器
func NewFilter() *Filter {
	return &Filter{
		Must:    make([]Condition, 0),
		Should:  make([]Condition, 0),
		MustNot: make([]Condition, 0),
	}
}

// AddMustCondition 添加Must条件
func (f *Filter) AddMustCondition(key string, value interface{}) *Filter {
	f.Must = append(f.Must, Condition{
		Key: key,
		Match: &MatchValue{
			Value: value,
		},
	})
	return f
}

// AddShouldCondition 添加Should条件
func (f *Filter) AddShouldCondition(key string, value interface{}) *Filter {
	f.Should = append(f.Should, Condition{
		Key: key,
		Match: &MatchValue{
			Value: value,
		},
	})
	return f
}

// AddMustNotCondition 添加MustNot条件
func (f *Filter) AddMustNotCondition(key string, value interface{}) *Filter {
	f.MustNot = append(f.MustNot, Condition{
		Key: key,
		Match: &MatchValue{
			Value: value,
		},
	})
	return f
}